package com.eolwral.osmonitor.messages;

import java.util.Locale;

import com.eolwral.osmonitor.OSMonitorService;
import com.eolwral.osmonitor.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.eolwral.osmonitor.preferences.Preferences;

public class LogcatBox extends DebugBox
{
	/**
	 * The PID of the process to watch for messages.
	 */
	private int targetPID = 0;

	@Override
	public void onResume()
	{
		if (getIntent().getExtras() != null)
		{
			targetPID = this.getIntent().getExtras().getInt("targetPID", 0);
			setTarget();
		}
		else
		{
			targetPID = 0;
			restorePrefs();
		}

		JNILibrary.TruncateLogcat();
		JNILibrary.doTaskStart(JNILibrary.doTaskLogcat);
		super.onResume();
	}

	@Override
	protected int getMessageCount()
	{
		return JNILibrary.GetLogcatCounts();
	}

	@Override
	protected String getLogMessage(int index, boolean html)
	{
		if (html)
			return String.format(Locale.US,
				"<tr><td>%s</td><td>[%s]</td><td>%s (%d)</td><td>%s</td></tr>\n",
				JNILibrary.GetLogcatTime(index),
				JNILibrary.GetLogcatLevel(index),
				JNILibrary.GetLogcatTag(index),
				JNILibrary.GetLogcatPID(index),
				JNILibrary.GetLogcatMessage(index));
		else
			return String.format(Locale.US, "%s [%s] %s (%d) %s\n",
				JNILibrary.GetLogcatTime(index),
				JNILibrary.GetLogcatLevel(index),
				JNILibrary.GetLogcatTag(index),
				JNILibrary.GetLogcatPID(index),
				JNILibrary.GetLogcatMessage(index));
	}

	private void setTarget()
	{
		// load settings
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);

		try
		{
			JNILibrary.doDataTime(Integer.parseInt(settings.getString(
					Preferences.PREF_UPDATE, "2")));
		}
		catch (Exception e)
		{
		}

		InternalList = (ListView) findViewById(R.id.debuglist);
		InternalList.setEmptyView(findViewById(R.id.debugempty));
		InternalList.setAdapter(new LogcatListAdapter(this));
		InternalList.setOnItemClickListener(InternalListListener);
		UpdateInterface = (LogcatListAdapter) InternalList.getAdapter();

		JNILibrary.SetLogcatFilter(1);
		JNILibrary.SetLogcatLevel(JNILibrary.doLogcatNONE);
		JNILibrary.SetLogcatMessage("");
		JNILibrary.SetLogcatSource(0);
		JNILibrary.SetLogcatPID(targetPID);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		TabIndex = 5;
		
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void restorePrefs()
	{
		// load settings
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);

		try
		{
			JNILibrary.doDataTime(Integer.parseInt(settings.getString(
					Preferences.PREF_UPDATE, "2")));
		}
		catch (Exception e)
		{
		}

		InternalList = (ListView) findViewById(R.id.debuglist);
		InternalList.setEmptyView(findViewById(R.id.debugempty));
		InternalList.setAdapter(new LogcatListAdapter(this));
		InternalList.setOnItemClickListener(InternalListListener);
		UpdateInterface = (LogcatListAdapter) InternalList.getAdapter();

		try
		{
			JNILibrary.SetLogcatSource(Integer.parseInt(settings.getString(
					Preferences.PREF_LOGCATSOURCE, "0")));
		}
		catch (Exception e)
		{
			JNILibrary.SetLogcatSource(0);
		}

		if (settings.getBoolean(Preferences.PREF_LOGCATUSEFILTER, false))
		{
			JNILibrary.SetLogcatFilter(1);
			JNILibrary.SetLogcatMessage(settings.getString(
					Preferences.PREF_LOGCATFILTERSTR, ""));

			try
			{
				JNILibrary.SetLogcatLevel(Integer.parseInt(settings.getString(
						Preferences.PREF_LOGCATFILTERLV, "0")));
			}
			catch (Exception e)
			{
				JNILibrary.SetLogcatLevel(0);
			}

			try
			{
				JNILibrary.SetLogcatPID(Integer.parseInt(settings.getString(
						Preferences.PREF_LOGCATFILTERPID, "0")));
			}
			catch (Exception e)
			{
				JNILibrary.SetLogcatPID(0);
			}
		}
		else
			JNILibrary.SetLogcatFilter(0);

		if (settings.getBoolean(Preferences.PREF_STATUSBAR, false))
		{
			if (OSMonitorService.getInstance() == null)
				startService(new Intent(this, OSMonitorService.class));
			else
				OSMonitorService.getInstance().Notify();
		}
		else if (OSMonitorService.getInstance() != null)
			OSMonitorService.getInstance().stopSelf();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu optionMenu)
	{
		super.onCreateOptionsMenu(optionMenu);
		if (targetPID != 0)
			optionMenu.add(0, 3, 0,
					getResources().getString(R.string.pref_filterlevel_text));

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case 1:
			if (targetPID == 0)
				break;
			return false;
		}

		return super.onOptionsItemSelected(item);
	}

	private OnItemClickListener InternalListListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id)
		{
			if (position > JNILibrary.GetLogcatCounts())
				position = JNILibrary.GetLogcatCounts();

			AlertDialog.Builder LogcatInfo = new AlertDialog.Builder(
					l.getContext());
			LogcatInfo.setMessage(JNILibrary.GetLogcatMessage(position));
			LogcatInfo.show();
		}
	};

	/**
	 * We will use a SpeechView to display each speech. It's just a LinearLayout
	 * with two text fields.
	 * 
	 */
	private class LogcatDetailView extends TableLayout
	{

		private TextView LogcatTitle;
		private TextView LogcatMsg;

		public LogcatDetailView(Context context, String Time, String Level,
				int PID, String Tag, String Msg, int position)
		{
			super(context);

			LogcatMsg = new TextView(context);
			LogcatTitle = new TextView(context);

			LogcatTitle.setGravity(Gravity.LEFT);

			LogcatMsg.setGravity(Gravity.LEFT);

			LogcatTitle.setText(Time + "  [" + Level + "]\n" + Tag + "(" + PID
					+ ")");

			if (Level.endsWith("ERROR"))
				LogcatTitle.setTextColor(Color.RED);
			else if (Level.endsWith("DEBUG"))
				LogcatTitle.setTextColor(Color.BLUE);
			else if (Level.endsWith("INFORMATION"))
				LogcatTitle.setTextColor(Color.GREEN);
			else if (Level.endsWith("WARNING"))
				LogcatTitle.setTextColor(Color.YELLOW);
			else if (Level.endsWith("VERBOSE"))
				LogcatTitle.setTextColor(Color.WHITE);

			String temp = JNILibrary.GetLogcatMessage(position);
			if (temp.length() > 200)
				LogcatMsg
						.setText("Message too long!! \nPlease click it to show..");
			else
				LogcatMsg.setText(temp.trim());

			addView(LogcatTitle);
			addView(LogcatMsg);

			if (position % 2 == 0)
				setBackgroundColor(0x80444444);
			else
				setBackgroundColor(0x80000000);

		}

		public void setContext(String Time, String Level, int PID, String Tag,
				String Msg, int position)
		{

			LogcatTitle.setText(Time + "  [" + Level + "]\n" + Tag + "(" + PID
					+ ")");

			if (Level.endsWith("ERROR"))
				LogcatTitle.setTextColor(Color.RED);
			else if (Level.endsWith("DEBUG"))
				LogcatTitle.setTextColor(Color.BLUE);
			else if (Level.endsWith("INFORMATION"))
				LogcatTitle.setTextColor(Color.GREEN);
			else if (Level.endsWith("WARNING"))
				LogcatTitle.setTextColor(Color.YELLOW);
			else if (Level.endsWith("VERBOSE"))
				LogcatTitle.setTextColor(Color.WHITE);

			String temp = JNILibrary.GetLogcatMessage(position);
			if (temp.length() > 150)
				LogcatMsg
						.setText("Message too long!! \nPlease click it to show..");
			else
				LogcatMsg.setText(temp.trim());

			if (position % 2 == 0)
				setBackgroundColor(0x80444444);
			else
				setBackgroundColor(0x80000000);

		}
	}

	private class LogcatListAdapter extends BaseAdapter
	{
		public LogcatListAdapter(Context context)
		{
			mContext = context;
		}

		public int getCount()
		{
			return JNILibrary.GetLogcatCounts();
		}

		public Object getItem(int position)
		{
			return position;
		}

		public long getItemId(int position)
		{
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			LogcatDetailView sv;

			if (convertView == null)
			{
				sv = new LogcatDetailView(mContext,
						JNILibrary.GetLogcatTime(position),
						JNILibrary.GetLogcatLevel(position),
						JNILibrary.GetLogcatPID(position),
						JNILibrary.GetLogcatTag(position),
						/* JNILibrary.GetLogcatMessage(position) */"", position);
			}
			else
			{
				sv = (LogcatDetailView) convertView;
				sv.setContext(JNILibrary.GetLogcatTime(position),
						JNILibrary.GetLogcatLevel(position),
						JNILibrary.GetLogcatPID(position),
						JNILibrary.GetLogcatTag(position),
						/* JNILibrary.GetLogcatMessage(position) */"", position);
			}

			return sv;
		}

		/**
		 * Remember our context so we can use it when constructing views.
		 */
		private Context mContext;
	}
}
